package com.fast.orm.utils;

import io.netty.util.concurrent.FastThreadLocal;

import java.util.HashMap;
import java.util.Map;

public class FastThreadLocalUtil {
    private static final Map<Class, FastThreadLocal<Object>> threadLocalMap = new HashMap<>();

    public static <T> T get(Class<T> clazz) {
        FastThreadLocal<T> threadLocal = getThreadLocal(clazz);
        T t = threadLocal.get();
        if (t == null) {
            try {
                t = clazz.newInstance();
                threadLocal.set(t);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return t;
    }

    public static <T> void set(Class<T> clazz, T t) {
        getThreadLocal(clazz).set(t);
    }

    public static <T> FastThreadLocal<T> getThreadLocal(Class<T> clazz) {
        FastThreadLocal<Object> fastThreadLocal = threadLocalMap.get(clazz);
        if (fastThreadLocal == null) {
            synchronized (FastThreadLocalUtil.class) {
                fastThreadLocal = threadLocalMap.get(clazz);
                if (fastThreadLocal == null) {
                    fastThreadLocal = new FastThreadLocal<>();
                    threadLocalMap.put(clazz, fastThreadLocal);
                }
            }
        }
        return (FastThreadLocal<T>) fastThreadLocal;
    }


}
